package com.ymatou.query.seller.trading.api.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.query.seller.trading.api.parameter.Common;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOderInfoByProductIdArguments;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOderInfoByProductIdResult;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOderInfoByProductIdResult.CatalogOrderInfo;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOderInfoByProductIdResult.CatalogOrderSummary;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOrderInfoByProductIdBean;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOrderInfoByProductIdResponse;
import com.ymatou.query.seller.trading.api.parameter.Sp_GetSellerOrderInfoByProductId;
import com.ymatou.query.seller.trading.api.service.GetSellerOderInfoByProductIdCall;
import com.ymatou.query.seller.trading.api.service.OrderCreate;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.common.entitie.C2COrderInfo;
import com.ymttest.common.entitie.C2COrderInfo.C2COrderInfoExt;
import com.ymttest.common.entitie.CatalogInfo;
import com.ymttest.common.enums.OrderStatusEnum;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.constant.ECode;

/**
 * 根据商品id获取买家相关订单信息
 */
@TestSuite
public class Ts_GetSellerOrderInfoByProductId {

	private static GetSellerOrderInfoByProductIdBean getSellerOderInfoByProductIdBean;
	private static GetSellerOderInfoByProductIdCall getSellerOderInfoByProductIdCall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("根据商品id获取买家相关订单信息");
	}

	@Before
	public void caseUp() {
		getSellerOderInfoByProductIdBean = new GetSellerOrderInfoByProductIdBean();
		getSellerOderInfoByProductIdCall = new GetSellerOderInfoByProductIdCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getSellerOderInfoByProductIdCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verify() {
		GetSellerOrderInfoByProductIdResponse expectedResponse = new GetSellerOrderInfoByProductIdResponse();

		ConstructExpectedResponse(expectedResponse);
		GetSellerOrderInfoByProductIdResponse actualResponse = getSellerOderInfoByProductIdCall
				.getSellerOrderInfoByProductIdResponse();
		
		Logger.comment("开始验证");
		DataUtil.verifyEquals(expectedResponse.getProductId(),
				actualResponse.getProductId(), "验证ProductId");
		DataUtil.verifyEquals(expectedResponse.getNotPaidOrderNum(),
				actualResponse.getNotPaidOrderNum(), "验证NotPaidOrderNum");
		DataUtil.verifyEquals(expectedResponse.getNotPaidOrderProductNum(),
				actualResponse.getNotPaidOrderProductNum(),
				"验证NotPaidOrderProductNum");
		DataUtil.verifyEquals(expectedResponse.getPaidOrderNum(),
				actualResponse.getPaidOrderNum(), "验证PaidOrderNum");
		DataUtil.verifyEquals(expectedResponse.getPaidOrderProductNum(),
				actualResponse.getPaidOrderProductNum(),
				"验证PaidOrderProductNum");
		DataUtil.verifyDateEquals(expectedResponse.getLastOrderTime(),
				actualResponse.getLastOrderTime(), "验证LastOrderTime");
		DataUtil.verifyEquals(expectedResponse.getCatalogList().size(),
				expectedResponse.getCatalogList().size(), "验证CatalogList的大小");
		for (CatalogInfo expect : expectedResponse.getCatalogList()) {
			boolean exists = actualResponse
					.getCatalogList()
					.stream()
					.anyMatch(
							x -> x.getCatalogId().equals(expect.getCatalogId()));
			DataUtil.verifyEquals(true, exists,
					"验证期望的CatalogId: " + expect.getCatalogId()
							+ "在CatalogList中是否存在");
			if (exists) {
				CatalogInfo actual = actualResponse
						.getCatalogList()
						.stream()
						.filter(x -> x.getCatalogId().equals(
								expect.getCatalogId()))
						.collect(Collectors.toList()).get(0);
				DataUtil.verifyEquals(expect.getOrderNum(),
						actual.getOrderNum(),
						"验证期望的CatalogId: " + expect.getCatalogId()
								+ "的OrderNum");
				DataUtil.verifyEquals(expect.getPurchasedNum(),
						actual.getPurchasedNum(),
						"验证期望的CatalogId: " + expect.getCatalogId()
								+ "的PurchasedNum");
			}
		}
		Logger.comment("验证结束");
	}

	/**
	 * @param response
	 */
	private void ConstructExpectedResponse(
			GetSellerOrderInfoByProductIdResponse response) {
		GetSellerOderInfoByProductIdArguments args = new GetSellerOderInfoByProductIdArguments();
		args.setSellerId(getSellerOderInfoByProductIdBean.getSellerId());
		args.setProductId(getSellerOderInfoByProductIdBean.getProductId());
		args.setOrderEstablishStatus(OrderStatusEnum.OrderEstablish.getValue());
		args.setOrderStatus(Common.OrderAvailiableStatus());
		GetSellerOderInfoByProductIdResult result = execute(args);

		response.setProductId(getSellerOderInfoByProductIdBean.getProductId());
		response.setLastOrderTime(result.getSummary().getLastOrderTime());
		response.setNotPaidOrderNum(result.getSummary().getNotPaidOrderCount());
		response.setPaidOrderNum(result.getSummary().getSoldOrderCount());
		response.setNotPaidOrderProductNum(result.getSummary()
				.getNotPaidCount());
		response.setPaidOrderProductNum(result.getSummary().getSoldCount());

		List<CatalogInfo> catalogList = new ArrayList<CatalogInfo>();
		if (DataUtil.isNullOrEmpty(result.getInfos()) == false) {
			for (CatalogOrderInfo o : result.getInfos()) {
				CatalogInfo info = new CatalogInfo();
				info.setCatalogId(o.getCatalogId());
				info.setOrderNum(o.getOrderCount());
				info.setPurchasedNum(o.getSoldCount());
				catalogList.add(info);
			}
		}
		response.setCatalogList(catalogList);
	}

	private GetSellerOderInfoByProductIdResult execute(
			GetSellerOderInfoByProductIdArguments args) {
		Sp_GetSellerOrderInfoByProductId sp = new Sp_GetSellerOrderInfoByProductId();
		sp.setProductId(args.getProductId());
		sp.setSellerId(args.getSellerId());
		sp.setOrderEstablishStatus(args.getOrderEstablishStatus());
		sp.setOrderStatus(args.getOrderStatus());
		sp.Execute();
		return ConvertResult(sp.getInfos(), sp.getSummary());
	}

	@SuppressWarnings("rawtypes")
	private GetSellerOderInfoByProductIdResult ConvertResult(List<Map> infos,
			Map summary) {
		GetSellerOderInfoByProductIdResult result = new GetSellerOderInfoByProductIdResult();
		List<CatalogOrderInfo> Infos = new ArrayList<GetSellerOderInfoByProductIdResult.CatalogOrderInfo>();
		CatalogOrderSummary Summary = new CatalogOrderSummary();
		if (DataUtil.isNullOrEmpty(infos) == false) {
			for (Map m : infos) {
				CatalogOrderInfo info = new CatalogOrderInfo();
				info.setCatalogId(DataUtil.Stringg.getValueOrDefault(m
						.get("catalogId")));
				info.setOrderCount((int) m.get("orderCount"));
				info.setSoldCount((int) m.get("soldCount"));
				Infos.add(info);
			}
		}
		if (summary.size() > 0) {
			Summary.setLastOrderTime(DataUtil.Stringg.getValueOrNull(summary
					.get("lastOrderTime")));
			Summary.setNotPaidCount((int) summary.get("notPaidCount"));
			Summary.setNotPaidOrderCount((int) summary.get("notPaidOrderCount"));
			Summary.setSoldCount((int) summary.get("soldCount"));
			Summary.setSoldOrderCount((int) summary.get("soldOrderCount"));
		}
		result.setInfos(Infos);
		result.setSummary(Summary);
		return result;
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrderInfoByProductId_001() {
		Logger.start(true, "根据商品id获取买家相关订单信息成功, 已支付订单");
		try {
			Logger.comment("准备数据");
			OrderCreate create = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			C2COrderInfoExt orderInfo = create.create4_ReceivedOrder(userId,
					sellerId);
			String ProductId = orderInfo.getsProductId();
			Logger.comment("数据准备结束");
			// 参数
			getSellerOderInfoByProductIdBean.setProductId(ProductId);
			getSellerOderInfoByProductIdBean.setSellerId(sellerId);
			// 发送请求
			getSellerOderInfoByProductIdCall
					.setData(getSellerOderInfoByProductIdBean);
			getSellerOderInfoByProductIdCall.callService();
			Logger.comment("getSellerOderInfoByProductIdCall send:"
					+ getSellerOderInfoByProductIdCall.getEntityString());
			Logger.comment("getSellerOderInfoByProductIdCall response:"
					+ getSellerOderInfoByProductIdCall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS,
					getSellerOderInfoByProductIdCall.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrderInfoByProductId_002() {
		Logger.start(true, "根据商品id获取买家相关订单信息成功, 未支付订单");
		try {
			Logger.comment("准备数据");
			OrderCreate create = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			C2COrderInfoExt orderInfo = create.create1_M2cOrder(userId, sellerId);
			String ProductId = orderInfo.getsProductId();
			Logger.comment("数据准备结束");
			// 参数
			getSellerOderInfoByProductIdBean.setProductId(ProductId);
			getSellerOderInfoByProductIdBean.setSellerId(sellerId);
			// 发送请求
			getSellerOderInfoByProductIdCall
					.setData(getSellerOderInfoByProductIdBean);
			getSellerOderInfoByProductIdCall.callService();
			Logger.comment("getSellerOderInfoByProductIdCall send:"
					+ getSellerOderInfoByProductIdCall.getEntityString());
			Logger.comment("getSellerOderInfoByProductIdCall response:"
					+ getSellerOderInfoByProductIdCall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS,
					getSellerOderInfoByProductIdCall.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrderInfoByProductId_003() {
		Logger.start(true, "根据商品id获取买家相关订单信息成功, 多个未支付订单");
		try {
			Logger.comment("准备数据");
			OrderCreate create = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			List<C2COrderInfo> orderInfos = create.create1_BatchC2COrder(userId, sellerId, 6);
			String ProductId = orderInfos.get(0).getsProductId();
			Logger.comment("数据准备结束");
			// 参数
			getSellerOderInfoByProductIdBean.setProductId(ProductId);
			getSellerOderInfoByProductIdBean.setSellerId(sellerId);
			// 发送请求
			getSellerOderInfoByProductIdCall
					.setData(getSellerOderInfoByProductIdBean);
			getSellerOderInfoByProductIdCall.callService();
			Logger.comment("getSellerOderInfoByProductIdCall send:"
					+ getSellerOderInfoByProductIdCall.getEntityString());
			Logger.comment("getSellerOderInfoByProductIdCall response:"
					+ getSellerOderInfoByProductIdCall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS,
					getSellerOderInfoByProductIdCall.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrderInfoByProductId_004() {
		Logger.start(true, "根据商品id获取买家相关订单信息成功, 多个已支付订单");
		try {
			Logger.comment("准备数据");
			OrderCreate create = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			List<C2COrderInfo> orderInfos = create.create1_BatchC2COrder(userId, sellerId, 6);
			String ProductId = orderInfos.get(0).getsProductId();
			ArrayList<Integer> orderIdList = new ArrayList<Integer>();
			OrderCallService ocs = new OrderCallService();
			for(C2COrderInfo orderInfo:orderInfos){
				orderIdList.add(orderInfo.getiOrderId());
			}
			BigDecimal payAmount = ocs.getNeedPrePayAmountOfCashBymainOrderId(orderInfos.get(0).getiTradingId());
			ocs.orderPayRequest(userId, payAmount, orderInfos.get(0).getiTradingId());
			ocs.batchAcceptOrders(sellerId, orderIdList);
			Logger.comment("数据准备结束");
			// 参数
			getSellerOderInfoByProductIdBean.setProductId(ProductId);
			getSellerOderInfoByProductIdBean.setSellerId(sellerId);
			// 发送请求
			getSellerOderInfoByProductIdCall
					.setData(getSellerOderInfoByProductIdBean);
			getSellerOderInfoByProductIdCall.callService();
			Logger.comment("getSellerOderInfoByProductIdCall send:"
					+ getSellerOderInfoByProductIdCall.getEntityString());
			Logger.comment("getSellerOderInfoByProductIdCall response:"
					+ getSellerOderInfoByProductIdCall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS,
					getSellerOderInfoByProductIdCall.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}